package com.farm.web.filter;

import java.io.IOException;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSONObject;
import com.farm.authority.domain.User;
import io.jsonwebtoken.Jwt;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.impl.DefaultClaims;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.MDC;

import com.farm.authority.FarmAuthorityService;
import com.farm.core.auth.domain.LoginUser;
import com.farm.web.WebUtils;
import com.farm.web.constant.FarmConstant;

public class FilterLogInfo implements Filter {

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
			throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) arg0;
		HttpSession session = req.getSession();
		// 获得EKCP的登录token,并登录系统
		{
			@SuppressWarnings("unchecked")
			Map<String, String[]> params = arg0.getParameterMap();
			String[] paras = params.get("ekcplogintoken");
			if (paras != null && params.get("ekcplogintoken").length > 0) {
				String ekcplogintoken = params.get("ekcplogintoken")[0];
				String userloginname = WebUtils.getTokenUsername(ekcplogintoken);
				if (userloginname != null) {
					FarmAuthorityService.loginIntoSession(session, WebUtils.getCurrentIp(req), userloginname,"获得token登录");
				}
			}
		}

		//todo:增加header头，用于自动登录系统；
		String jwt = ((HttpServletRequest) arg0).getHeader("Jwt");
		if(StringUtils.isEmpty(jwt)) {
			jwt = ((HttpServletRequest) arg0).getParameter("Jwt");
			if(StringUtils.isEmpty(jwt)){
				jwt = ((HttpServletRequest) arg0).getParameter("jwt");
			}
		}
//		jwt = "eyJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE2MDExMjU5MjYsInN1YiI6IntcImFjY2Vzc190b2tlblwiOlwiXCIsXCJpc3V1ZWRBdFwiOjE2MDExMjU5MjY2OTgsXCJ1c2VyX29yZ19jb2RlXCI6XCIzNjAxMDExOTNcIixcInVzZXJfb3JnX2tleVwiOlwiZmYxNmE0YWRlZDFiNDFiZGFhMGNmZDIwMzE2NzQ0NWRcIixcInVzZXJfbmFtZVwiOlwi5rKI5rexXCIsXCJ1c2VyX29yZ196Yl9jb2RlXCI6XCIwMzYwODM1NTU4MDNcIixcInVzZXJfb3JnX25hbWVcIjpcIuS4reWFseWGheiSmeWPpOiHquayu-WMulwiLFwidXNlcl9rZXlcIjpcIjJiZmIxNmVlMjU1MDQ2YTI4NzliYjhlMDNhZWJiOTNjXCIsXCJhY2NvdW50XCI6XCJqc2RqMTk5MjIyOTY5MDJiODcxXCJ9In0.SpHiHozKYqx4n2YNhy0c6XGisuR0D7DOCTtnBK-ZLUU";
		if(StringUtils.isNotEmpty(jwt)){
			//如果有jwt头，则自动进行解析和登录；
			Jwt jwtObj = Jwts.parser().setSigningKey("wtSB6432432fdshi#%%27lkebFrfJWLBmfhtyJbpF1L17F7XrGX").parse(jwt);
			DefaultClaims claims = (DefaultClaims)jwtObj.getBody();
			JSONObject jsonObject = JSONObject.parseObject(claims.getSubject());
			String account = jsonObject.getString("account");
			String user_key = jsonObject.getString("user_key");
			String user_name = jsonObject.getString("user_name");
			String user_org_name = jsonObject.getString("user_org_name");
			User user = new User();
			user.setName(user_name);
			user.setLoginname(account);
			user.setType("1");
			user.setId(user_key);
			user.setIp(WebUtils.getCurrentIp((HttpServletRequest) arg0));
			user.setState("1");
			user.setImgid("2c902a8d67085e660167086948800011");
			FarmAuthorityService.loginIntoSessionAuto(session,user,"jwt免密登录");
		}

		// 写入log4j的用户信息
		MDC.put("IP", arg0.getRemoteAddr());
		if (session == null) {
			MDC.put("USERID", "NONE");
		} else {
			LoginUser user = (LoginUser) session.getAttribute(FarmConstant.SESSION_USEROBJ);
			if (user == null) {
				MDC.put("USERID", "NONE");
			} else {
				MDC.put("USERID", user.getId());
			}
		}
		arg2.doFilter(arg0, arg1);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

}
